importScripts('./comm.js')

function Socket() {
    this.ws = null;

    this.timer = null; // 延迟计时器

    this.decodeFlag = false; // 是否推送 信息至主线程

    this.heartbeatTimer = null; // 心跳计时器

}

function sum(m, n) {
    return Math.round(Math.random() * (m - n) + n);
}

function randomCoding() {
    let result = [];
    let n = 4; //这个值可以改变的，对应的生成多少个字母，根据自己需求所改
    for (let i = 0; i < n; i++) {
        //生成一个0到25的数字
        let ranNum = Math.ceil(Math.random() * 25);
        //大写字母'A'的ASCII是65,A~Z的ASCII码就是65 + 0~25;
        //然后调用String.fromCharCode()传入ASCII值返回相应的字符并push进数组里
        result.push(String.fromCharCode(65 + ranNum));
    }
    return result.join('');
}

Socket.prototype.requestWebsocket = function (url, did,dtype) {
    // 创建 web socket 连接
    url = url != '' ? url : "ws://58.215.50.61:8309/dpe/websocket/app/cmd?appName=monitor&userId=" + `${sum(1,9999) +randomCoding()}` + "&userToken=b16729f03823420aa3ba909f2f36f100&initSendAllData=0&clientId=478720";
    this.ws = new WebSocket(url);
    this.ws.binaryType = 'arraybuffer'
    let that = this;

    this.ws.onopen = function (msg) {
        // 数据绑定 牵手
        that.ws.send(
            JSON.stringify({
                'wsCmd': 'applyLiveStream',
                'params': {
                    audio: 1,
                    cameraChannelId: 0,
                    cid: `${sum(1,555) +randomCoding()}`,
                    did: did,
                    streamProtocol: dtype,
                }
            })
        )

    }

    this.ws.onmessage = function (msg) {
        // 数据传递
        // 启动定时器  监听 ws 是否卡顿  如果卡顿 将消息传回主线程
        let data = msg.data;
        if (typeof data == 'string') {
            // 初始化 websocket 连接

            data = JSON.parse(data)
            if (data.params == undefined) {
                // 清理数据
                return
            }
            if (data.params.r == 0) {
                let o = {
                    state: SocketStateInitSucc // 表示 websocket 准备完毕
                }
                self.postMessage(o)
            } else {
                // ws 连接出错
                let o = {
                    state: SocketStateInitErr,
                    message: data.params.rn
                }
                self.postMessage(o)
            }

        } else {
            // 判断 解码器是否初始化完成
            if (that.decodeFlag) {
                self.socket.monitor()
                let o = {
                    state: SocketStateSucc,
                    data: data,
                    size: data.byteLength,
                   
                }


                self.postMessage(o, [o.data])
                // self.socket.ws.close()
                // 重置 定时器
                if (self.socket.timer !== null) {
                    clearTimeout(self.socket.timer)
                    self.socket.timer = null
                }


                

                that.wsTimer()

            } else {
                self.socket.timer = null;
            }

        }


        data = null
    }

    this.ws.onerror = function (msg) {

    }

    this.ws.onclose = function (msg) {
        clearInterval(that.heartbeatTimer)
        console.error('ws 已关闭')
    }
}

Socket.prototype.monitor = function () {
    // 监听 ws 是否会有延迟  
    self.socket.timer = setTimeout(() => {
        let o = {
            state: SocketStateTimeout,
        }
        self.postMessage(o)
    }, 200)
}


Socket.prototype.wsTimer = function () {
    let that = this;
    if (that.heartbeatTimer !== null) {
        return
    }
    that.heartbeatTimer = setInterval(function () {
        that.ws.send(JSON.stringify({
            'wsCmd': 'heartbeat',
            'params': {}
        }))
    }, 5000)
}



self.socket = new Socket;

self.onmessage = function (msg) {
    // socket 线程
    let data = msg.data;

    switch (data.state) {
        case WasmLoaded:
            // wasm 已成功读取  可进行 socket 链接
            this.socket.requestWebsocket(data.url, data.did, data.dtype)
            break;
        case DecodeStateInitSucc:
            // decode 已初始化 可推送
            this.socket.decodeFlag = true
            break;
        case SocketStateClose:
            if (this.socket.ws.close()) {
                this.socket.ws.close();
            }
            break;
        case SocketStatePause:
            // 传输暂停
            this.socket.decodeFlag = false;
            break;
    }
}